//
//  XUIPreviewImageViewInternal.m
//  etionUI
//
//  Created by wangjian on 1/28/13.
//
//

#import "XUIPreviewImageViewInternal.h"

#define VISIBLE_VIEW_NUM 3

@implementation XUIPreviewImageViewInternalCell

@synthesize imageOriginalSize = _imageOriginalSize;
@synthesize imageView = _imageView;
@synthesize activity = _activity;
@synthesize zoomScrollView = _zoomScrollView;
@synthesize szTag;

- (id)initWithBrowserStyle:(EViewBrowserCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super init])
    {
        _zoomScrollView = [[UIScrollView alloc] init];
        _zoomScrollView.center = self.center;
        _zoomScrollView.delegate = self;
        _zoomScrollView.backgroundColor = [UIColor clearColor];
//        _zoomScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
        [self addSubview:_zoomScrollView];
        
        _imageView = [[UIImageView alloc] init];
        _imageView.center = _zoomScrollView.center;
        [_zoomScrollView addSubview:_imageView];
        
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _activity.center = self.center;
        _activity.hidesWhenStopped = YES;
        [self addSubview:_activity];
        
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        self.autoresizesSubviews = YES;
    }
    
    return self;
}

- (void)resetViewsFrame
{
    _zoomScrollView.frame = self.bounds;
    _zoomScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    _zoomScrollView.contentSize = CGSizeZero;
    _zoomScrollView.zoomScale = 1.0;
    _zoomScrollView.contentOffset = CGPointZero;
    _zoomScrollView.minimumZoomScale = 1 / 4;
    _zoomScrollView.maximumZoomScale = 4;
    
//    CGFloat viewW = 0, viewH = 0;
//    CGFloat mul = [UIImage caleFitImageSize:_imageOriginalSize targetSize:_zoomScrollView.frame.size width:&viewW height:&viewH];
//    if (mul < 1)
//        _zoomScrollView.maximumZoomScale = 1 / mul;
//    else if (mul > 1)
//        _zoomScrollView.minimumZoomScale = 1 / mul;
//    if (_zoomScrollView.maximumZoomScale < 4)
//    {
//        _zoomScrollView.maximumZoomScale = 4;
//    }
    
    CGSize size = [UIImage imageNewSizeFromImageSize:_imageOriginalSize zoomToSize:_zoomScrollView.frame.size];
    
    _imageView.frame = CGRectMake((_zoomScrollView.width - size.width) / 2, (_zoomScrollView.height - size.height) / 2, size.width, size.height);
    _imageView.center = CGPointMake(CGRectGetWidth(_zoomScrollView.frame)/2, CGRectGetHeight(_zoomScrollView.frame)/2);
    _zoomScrollView.contentSize = _imageView.size;
    _activity.center = CGPointMake(self.width/2, self.height/2);
}

- (void)resetViews
{
    _zoomScrollView.maximumZoomScale = 1.0;
    _zoomScrollView.minimumZoomScale = 1.0;
    _zoomScrollView.zoomScale = 1.0;
    [self disableActivityIndicator];
}

- (void)dealloc
{
    [_imageView release_mm];
    [_activity release_mm];
    [_zoomScrollView release_mm];
    self.szTag = nil;
    superdealloc_mm;
}

- (void)enableActivityIndicator
{
    [_activity startAnimating];
}

- (void)disableActivityIndicator
{
    [_activity stopAnimating];
}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _imageView;
}

-(void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
	scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    if(scrollView.zoomScale < 1.00)
        _imageView.center = CGPointMake(CGRectGetWidth(scrollView.frame)/2, CGRectGetHeight(scrollView.frame)/2);
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    CGRect frame = _imageView.frame;
    if(frame.size.width>scrollView.frame.size.width || frame.size.height>scrollView.frame.size.height)
    {
        if(frame.size.width>scrollView.frame.size.width && frame.size.height>scrollView.frame.size.height)
            scrollView.contentInset = UIEdgeInsetsMake(-frame.origin.y, -frame.origin.x, frame.origin.y, frame.origin.x);
        else if(frame.size.width>scrollView.frame.size.width && frame.size.height<=scrollView.frame.size.height)
            view.center = CGPointMake(view.center.x, CGRectGetHeight(scrollView.frame)/2);
        else
            view.center = CGPointMake(CGRectGetWidth(scrollView.frame)/2, view.center.y);
    }
    else
    {
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        view.center = CGPointMake(CGRectGetWidth(scrollView.frame)/2, CGRectGetHeight(scrollView.frame)/2);
    }
}

@end

@implementation XUIPreviewImageViewInternal

@synthesize currentIndex = _currentIndex;
@synthesize delegate = _delegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.bounces = NO;
        _scrollView.backgroundColor = [UIColor clearColor];
        _scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _scrollView.autoresizesSubviews = YES;
        [self addSubview:_scrollView];
        
        _dicCellIndex = [NSMutableDictionary new];
        
        UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureResponse:)] autorelease_mm];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [self addGestureRecognizer:tapGesture];
        
        _sortFun = ^NSComparisonResult(id obj1, id obj2)
        {
            NSUInteger i = [obj1 integerValue];
            NSUInteger j = [obj2 integerValue];
            if(i > j)
                return NSOrderedDescending;
            else if(i < j)
                return NSOrderedAscending;
            return NSOrderedSame;
        };
    }
    return self;
}

- (void)dealloc
{
    [_scrollView release_mm];
    [_dicCellIndex release_mm];
    superdealloc_mm;
}

- (void)reloadView
{
    NSInteger nViewNum = [_delegate numberOfViews:self];
    
    _scrollView.contentSize = CGSizeMake(self.width * nViewNum, self.height);
    _scrollView.contentOffset = CGPointZero;
    
    _currentIndex = 0;
    
    for (NSUInteger i = 0; i < nViewNum; i++)
    {
        [self reloadCellViewAtIndex:i];
    }
    
    [_delegate previewImageViewInternal:self didShowViewAtIndex:0];
}

- (void)deleteCellAtIndex:(NSUInteger)index
{
    XUIPreviewImageViewInternalCell *cellView = [_dicCellIndex objectForKey:@(index)];
    [cellView removeFromSuperview];
    
    [_dicCellIndex removeObjectForKey:@(index)];
    _scrollView.contentSize = CGSizeMake(self.width * _dicCellIndex.count, self.height);
    
    _currentIndex = _scrollView.contentOffset.x / _scrollView.width;
    
    if(_dicCellIndex.count >0 )
    {
        NSMutableArray *tmp = [NSMutableArray new];
        NSMutableDictionary *dic = [NSMutableDictionary new];
        NSArray *indexs = [[_dicCellIndex allKeys] sortedArrayUsingComparator:_sortFun];
        for(NSUInteger i = index; i< indexs.count ;i++)
        {
            NSNumber *keyIndex = indexs[i];
            XUIPreviewImageViewInternalCell *cell = _dicCellIndex[keyIndex];
            cell.left -= cell.width;
            [tmp addObject:keyIndex];
            dic[@(i)] = cell;
        }
        [_dicCellIndex removeObjectsForKeys:tmp];
        [_dicCellIndex addEntriesFromDictionary:dic];
        
        if(_dicCellIndex.count > index)
        {
            
        }
        else
        {
            index = _dicCellIndex.count - 1;
        }
        
        cellView = _dicCellIndex[@(index)];
        [cellView resetViewsFrame];
        
        [_delegate previewImageViewInternal:self didShowViewAtIndex:index];
    }
}

- (void)selectCellAtIndex:(NSUInteger)index
{
    _scrollView.contentOffset = CGPointMake(self.width * index, 0);
    
    _currentIndex = _scrollView.contentOffset.x / _scrollView.width;
    
//    [self reloadCellViewAtIndex:index];
    
    [_delegate previewImageViewInternal:self didShowViewAtIndex:index];

}

- (void)resetViewContentLocation:(UIInterfaceOrientation)toInterfaceOrientation
{
    CGFloat w = self.width;
    CGFloat h = self.height;
    if(UIInterfaceOrientationIsLandscape(toInterfaceOrientation))
    {
        w = MAX(w, h);
        h = MIN(w, h);
    }
    else
    {
        w = MIN(w, h);
        h = MAX(w, h);
    }
    
    _scrollView.contentSize = CGSizeMake(w * _dicCellIndex.count, h);
    _scrollView.contentOffset = CGPointMake(w * _currentIndex, 0);
    
    [_dicCellIndex enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
        XUIPreviewImageViewInternalCell *cellView = obj;
        NSInteger index = [key integerValue];
        cellView.frame = CGRectMake(index * w, 0, w, h);
        [cellView resetViewsFrame];
    }];
}

- (void)reloadCellViewAtIndex:(NSUInteger)index
{
    if(_dicCellIndex.count > 0)
    {
        XUIPreviewImageViewInternalCell *originCellView = _dicCellIndex[@(index)];
        [originCellView removeFromSuperview];
        [_dicCellIndex removeObjectForKey:@(index)];
    }
    
    XUIPreviewImageViewInternalCell *cellView = [_delegate previewImageViewInternal:self cellViewAtIndex:index];
    cellView.frame = CGRectMake(self.width * index, 0, self.width, self.height);
    [cellView resetViewsFrame];
    
    _dicCellIndex[@(index)] = cellView;

    [_scrollView addSubview:cellView];
}

-(void)tapGestureResponse:(UITapGestureRecognizer *)tapgesture
{
    if ([_delegate respondsToSelector:@selector(previewImageViewInternal:clickViewAtIndex:)])
    {
        [_delegate previewImageViewInternal:self clickViewAtIndex:_currentIndex];
    }
}

- (void)enableActivityIndicatorAtIndex:(NSUInteger)index
{
    XUIPreviewImageViewInternalCell *cellView = _dicCellIndex[@(index)];
    if (cellView != nil)
    {
        [cellView enableActivityIndicator];
    }
}

- (void)disableActivityIndicatorAtIndex:(NSUInteger)index
{
    XUIPreviewImageViewInternalCell *cellView = _dicCellIndex[@(index)];
    if (cellView != nil)
    {
        [cellView disableActivityIndicator];
    }
}

- (void)updateCellAtIndex:(NSUInteger)index withImage:(UIImage *)image originalSize:(CGSize)size animated:(BOOL)animated
{
    void(^fun)()=^
{
    XUIPreviewImageViewInternalCell *cellView = _dicCellIndex[@(index)];
    if (cellView != nil)
    {
        cellView.imageOriginalSize = size;
        cellView.imageView.image = image;
        [cellView resetViewsFrame];
    }
    };
    if(animated == YES)
    {
        [UIView animateWithDuration:0.3 animations:^
        {
            fun();
        }];
    }
    else
        fun();
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _scrollView)
    {
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (NO == [scrollView isEqual:_scrollView])
    {
        return;
    }
    
    NSUInteger showId = scrollView.contentOffset.x / _scrollView.width;
    if (showId == _currentIndex)
    {
        return;
    }
    
    if ([_delegate respondsToSelector:@selector(previewImageViewInternal:didShowViewAtIndex:)])
    {
        [_delegate previewImageViewInternal:self didShowViewAtIndex:showId];
    }
    if ([_delegate respondsToSelector:@selector(previewImageViewInternal:didHideViewAtIndex:)])
    {
        [_delegate previewImageViewInternal:self didHideViewAtIndex:_currentIndex];
    }
    _currentIndex = showId;
    
    [_delegate previewImageViewInternal:self didScrollToNewIndex:_currentIndex];
}

@end
